package com.su.dolphin.utils.mgr;

import java.util.Stack;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

/**
 * 不是真正意义上的ActivityMnager 而是管理App中的Activity
 */
public class DpActivityManager {
	private Stack<Activity> activityStack;
	private static DpActivityManager instance;

	private DpActivityManager() {
	}

	public static DpActivityManager i() {
		if (instance == null) {
			instance = new DpActivityManager();
		}
		return instance;
	}

	public void addActivity(Activity activity) {
		if (activityStack == null) {
			activityStack = new Stack<Activity>();
		}
		activityStack.add(activity);
	}

	/**
	 * 获取当前Activity（堆栈中最后一个压入的）
	 */
	public Activity getCurrentActivity() {
		Activity activity = activityStack.lastElement();
		return activity;
	}

	/**
	 * 结束当前Activity（堆栈中最后一个压入的）
	 */
	public void finishActivity() {
		Activity activity = activityStack.lastElement();
		finishActivity(activity);
	}

	/**
	 * 结束指定的Activity
	 */
	public void finishActivity(Activity activity) {
		if (activity != null) {
			activityStack.remove(activity);
			activity.finish();
			activity = null;
		}
	}

	/**
	 * 结束指定类名的Activity
	 */
	public void finishActivity(Class<?> cls) {
		for (Activity activity : activityStack) {
			if (activity.getClass().equals(cls)) {
				finishActivity(activity);
			}
		}
	}

	public void startActivity(Context context,
			Class<? extends Activity> activity) {
		Intent intent = new Intent(context, activity);
		context.startActivity(intent);
	}

	public void startActivity(Context context,
			Class<? extends Activity> activity, Bundle bundle) {
		Intent intent = new Intent(context, activity);
		intent.putExtras(bundle);
		context.startActivity(intent);
	}

	/**
	 * 退出应用程序
	 */
	public void finishApp(Context context) {
		try {
			finishAllActivity();
			// ActivityManager activityMgr= (ActivityManager)
			// context.getSystemService(Context.ACTIVITY_SERVICE);
			// activityMgr.restartPackage(context.getPackageName());
			System.exit(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void finishAllActivity() {
		for (int i = 0, size = activityStack.size(); i < size; i++) {
			if (null != activityStack.get(i)) {
				activityStack.get(i).finish();
			}
		}
		activityStack.clear();
	}
}
